package com.xmut.mall.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xmut.mall.order.entity.*;
import com.xmut.mall.order.feign.StoreFeignService;
import com.xmut.mall.order.myenum.*;
import com.xmut.mall.order.searchparam.AfterSaleSearchParams;
import com.xmut.mall.order.service.*;
import com.xmut.mall.order.to.*;
import com.xmut.mall.order.utils.*;
import com.xmut.mall.order.vo.AfterSaleApplyVO;
import com.xmut.mall.order.vo.AfterSaleVO;
import com.xmut.mall.order.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xmut.mall.order.dao.AfterSaleDao;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("afterSaleService")
public class AfterSaleServiceImpl extends ServiceImpl<AfterSaleDao, AfterSaleEntity> implements AfterSaleService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderLogService orderLogService;

    @Autowired
    private AfterSaleLogService afterSaleLogService;

    @Autowired
    private StoreFeignService storeFeignService;


    /**
     * 获取售后信息
     *
     * @param params
     * @return
     */
    @Transactional
    @Override
    public RespBean getAfterSaleInfo(Map<String, Object> params) {
        Long itemId = MapUtil.getLong(params, "itemId");

        AfterSaleApplyVO vo = new AfterSaleApplyVO();
        // 查找出进行售后的订单项
        OrderItemEntity orderItem = orderItemService.getById(itemId);
        //未申请售后订单货物或部分售后才能进行申请
        if (!orderItem.getAfterSaleStatus().equals(OrderItemAfterSaleStatusEnum.NOT_APPLIED.name())
                && !orderItem.getAfterSaleStatus().equals(OrderItemAfterSaleStatusEnum.PART_AFTER_SALE.name())) {
            return RespBean.error("订单状态不允许申请售后，请联系平台或商家");
        }
        OrderEntity order = orderService.getOne(new QueryWrapper<OrderEntity>().eq("sn", orderItem.getOrderSn()));
        //订单未支付，不能申请申请售后
        if (order.getPaymentMethod() == null) {
            return RespBean.error("当前订单未支付，不能申请售后");
        }
        //判断支付方式是否为线上支付
        if (order.getPaymentMethod().equals(PaymentMethodEnum.BANK_TRANSFER.name())) {
            vo.setRefundWay(AfterSaleRefundWayEnum.OFFLINE.name());
        } else {
            vo.setRefundWay(AfterSaleRefundWayEnum.ORIGINAL.name());
        }

        //判断订单类型，虚拟订单只支持退款
        if (order.getOrderType().equals(OrderTypeEnum.VIRTUAL.name())) {
            vo.setReturnMoney(true);
            vo.setReturnGoods(false);
        } else {
            vo.setReturnMoney(true);
            vo.setReturnGoods(true);
        }
        vo.setAccountType(order.getPaymentMethod());
        vo.setApplyRefundPrice(orderItem.getFlowPrice());
        vo.setNum(orderItem.getNum());
        vo.setGoodsId(orderItem.getGoodsId());
        vo.setGoodsName(orderItem.getGoodsName());
        vo.setImage(orderItem.getImage());
        vo.setGoodsPrice(orderItem.getGoodsPrice());
        vo.setSkuId(orderItem.getSkuId());
        vo.setMemberId(order.getMemberId());
        return RespBean.success("获取成功", vo);
    }

    /**
     * 申请售后
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean applyAfterSale(AfterSaleDTO dto) {
        //检查当前订单是否可申请售后
        if (!this.checkAfterSaleType(dto)) {
            return RespBean.error("当前订单不可售后");
        }

        //添加售后
        return addAfterSale(dto);

    }

    /**
     * 获取售后数据的分页信息
     *
     * @param vo
     * @param params
     * @return
     */
    @Override
    public RespBean getAfterSalePage(PageVO vo, AfterSaleSearchParams params) {
        IPage<AfterSaleVO> page = this.baseMapper.getAfterSalePage(PageUtil.initPage(vo), params);

        return RespBean.success("获取成功", page);
    }

    /**
     * 根据售后的sn号码获取售后的详情信息
     *
     * @param sn
     * @return
     */
    @Override
    public RespBean getAfterSaleDetail(String sn) {
        AfterSaleVO vo = this.baseMapper.getAfterSaleDetail(sn);

        return RespBean.success("获取成功", vo);

    }

    /**
     * 获取商家售后收件地址
     *
     * @param sn
     * @return
     */
    @Override
    public RespBean getStoreAfterSaleAddress(String sn) {
        StoreAfterSaleAddressDTO dto = this.getStoreAfterSaleAddressDTO(getBySn(sn).getStoreId());
        return RespBean.success("获取成功", dto);

    }

    /**
     * 审核售后申请
     *
     * @param dto
     * @return
     */
    @Override
    public RespBean review(SellerAfterSaleReviewDto dto) {
        //根据售后单号获取售后单
        AfterSaleEntity afterSale = getBySn(dto.getSn());

        /**
         * 前置判断 判断当前订单是否可操作性
         */
        // 判断为待审核的售后服务
        if (!afterSale.getServiceStatus().equals(AfterSaleStatusEnum.APPLY.name())) {
            return RespBean.error("售后已审核，无法重复操作");
        }
        //判断退款金额与付款金额是否正确,二者必须相等
        if (afterSale.getFlowPrice().compareTo(dto.getActualRefundPrice()) != 0) {
            return RespBean.error("订单退款金额不一致");
        }
        afterSale.setActualRefundPrice(dto.getActualRefundPrice());

        //判断审核状态
        //如果售后类型为：退款，审核状态为已通过并且退款方式为原路退回，售后单状态为已完成。
        //如果售后类型为：退款，审核状态已通过并且退款方式为线下退回，售后单状态为待退款。
        //如果售后类型不为退款，售后单状态为：已通过。
        AfterSaleStatusEnum afterSaleStatusEnum;
        if (dto.getServiceStatus().equals(AfterSaleStatusEnum.PASS.name())) {
            if (afterSale.getServiceType().equals(AfterSaleTypeEnum.RETURN_MONEY.name())) {
                if (afterSale.getRefundWay().equals(AfterSaleRefundWayEnum.ORIGINAL.name())) {
                    //如果为退款操作 && 在线支付 则直接进行退款
//                    refundSupport.refund(afterSale); // 退款功能还未开发
                    afterSaleStatusEnum = AfterSaleStatusEnum.COMPLETE;
                } else {
                    afterSaleStatusEnum = AfterSaleStatusEnum.WAIT_REFUND;
                }
            } else {
                afterSaleStatusEnum = AfterSaleStatusEnum.PASS;
            }
        } else {
            afterSaleStatusEnum = AfterSaleStatusEnum.REFUSE;
        }
        afterSale.setServiceStatus(afterSaleStatusEnum.name());
        afterSale.setAuditRemark(dto.getRemark());


        //根据售后状态。修改OrderItem订单中正在售后商品数量及状态
        OrderItemEntity orderItem = orderItemService.getOne(new QueryWrapper<OrderItemEntity>()
                .eq("order_sn", afterSale.getOrderSn())
                .eq("sku_id", afterSale.getSkuId()));
        afterSaleStatusEnum = AfterSaleStatusEnum.valueOf(afterSale.getServiceStatus());
        switch (afterSaleStatusEnum) {
            //判断当前售后的状态---申请中
            case APPLY: {
                orderItem.setReturnGoodsNumber(orderItem.getReturnGoodsNumber() + afterSale.getNum());
                break;
            }

            //判断当前售后的状态---已拒绝,买家取消售后,卖家终止售后
            case REFUSE:
            case BUYER_CANCEL:
            case SELLER_TERMINATION: {
                orderItem.setReturnGoodsNumber(orderItem.getReturnGoodsNumber() - afterSale.getNum());
                break;
            }
            default:
                break;
        }
        orderItem.setAfterSaleStatus(AfterSaleStatusEnum.valueOf(dto.getServiceStatus()).name());

        // 生成日志
        OrderLogEntity orderLog = new OrderLogEntity();
        orderLog.setOrderSn(afterSale.getOrderSn());
        orderLog.setCreateTime(new Date());
        orderLog.setOperatorType(dto.getOperatorType());
        orderLog.setOperatorId(dto.getOperatorId());
        orderLog.setOperatorName(dto.getOperatorName());
        orderLog.setMessage("订单[" + afterSale.getOrderSn() + "] 售后申请结果:" + AfterSaleStatusEnum.valueOf(dto.getServiceStatus()).description());

        AfterSaleLogEntity afterSaleLog = new AfterSaleLogEntity();
        afterSaleLog.setSn(afterSale.getSn());
        afterSaleLog.setCreateTime(new Date());
        afterSaleLog.setOperatorType(dto.getOperatorType());
        afterSaleLog.setOperatorId(dto.getOperatorId());
        afterSaleLog.setOperatorName(dto.getOperatorName());
        afterSaleLog.setMessage("审核售后:售后编号[" + afterSale.getSn() + " 结果:" + AfterSaleStatusEnum.valueOf(dto.getServiceStatus()).description());

        // 保存
        orderLogService.save(orderLog);
        afterSaleLogService.save(afterSaleLog);
        boolean updateAfterSale = this.updateById(afterSale);
        boolean updateOrderItem = orderItemService.updateById(orderItem);

        if (updateAfterSale && updateOrderItem) {
            return RespBean.success("审核成功");

        } else {
            return RespBean.error("审核错误");
        }


    }

    /**
     * 卖家 退货 物流接口
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public RespBean BuyerDelivery(BuyerDeliveryDto dto) {
        AfterSaleEntity afterSale = getBySn(dto.getAfterSaleSn());

        //判断为已审核通过，待邮寄的售后服务
        if (!afterSale.getServiceStatus().equals(AfterSaleStatusEnum.PASS.name())) {
            return RespBean.error("售后状态错误，请刷新页面");
        }

        //查询会员回寄的物流公司信息
        RespBean logisticsByIdResp = storeFeignService.getLogisticsById(dto.getLogisticsId());

        if (logisticsByIdResp.getObj() == null) {
            return RespBean.error("该物流公司不存在");
        }

        LogisticsEntityDto logistics = JSON.parseObject(JSON.toJSONString(logisticsByIdResp.getObj()), LogisticsEntityDto.class);

        afterSale.setMLogisticsCode(logistics.getId());
        afterSale.setMLogisticsName(logistics.getName());
        afterSale.setMLogisticsNo(dto.getLogisticsNo());
        afterSale.setMDeliverTime(dto.getMDeliverTime());
        //修改售后单状态
        afterSale.setServiceStatus(AfterSaleStatusEnum.BUYER_RETURN.name());
        // 修改保存
        // 生成日志
        AfterSaleLogEntity afterSaleLog = new AfterSaleLogEntity();
        afterSaleLog.setSn(dto.getAfterSaleSn());
        afterSaleLog.setCreateTime(new Date());
        afterSaleLog.setOperatorType(UserEnums.MEMBER.name());
        afterSaleLog.setOperatorId(dto.getMemberId());
        afterSaleLog.setOperatorName(dto.getUsername());
        afterSaleLog.setMessage("买家退货,物流填写:售后单号[" + dto.getAfterSaleSn() + "]，用户填写退货物流单号为[" + dto.getLogisticsNo() + "]");

        afterSaleLogService.save(afterSaleLog);

        boolean b = this.updateById(afterSale);

        if (b) {
            return RespBean.success("成功");
        } else {
            return RespBean.error("失败");
        }
    }

    /**
     * 获取售后退货商品的售后物流信息
     *
     * @param sn
     * @return
     */
    @Override
    public RespBean getAfterSaleTraces(String sn) {
        // 都是假的物流单号 这里直接给null了

        return RespBean.success("获取成功");

    }

    /**
     * 取消售后
     *
     * @param dto
     * @return
     */
    @Override
    public RespBean cancel(CancelAfterSaleDto dto) {
        AfterSaleEntity afterSale = getBySn(dto.getAfterSaleSn());

        //判断售后单是否可以申请售后
        //如果售后状态为：待审核、已通过则可进行申请售后
        if (afterSale.getServiceStatus().equals(AfterSaleStatusEnum.APPLY.name())
                || afterSale.getServiceStatus().equals(AfterSaleStatusEnum.PASS.name())) {

            afterSale.setServiceStatus(AfterSaleStatusEnum.BUYER_CANCEL.name());


            //根据售后状态。修改OrderItem订单中正在售后商品数量及状态
//            this.updateOrderItemAfterSaleStatus(afterSale);
            OrderItemEntity orderItem = orderItemService.getOne(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", afterSale.getOrderSn())
                    .eq("sku_id", afterSale.getSkuId()));
            AfterSaleStatusEnum afterSaleStatusEnum = AfterSaleStatusEnum.valueOf(afterSale.getServiceStatus());
            switch (afterSaleStatusEnum) {
                //判断当前售后的状态---申请中
                case APPLY: {
                    orderItem.setReturnGoodsNumber(orderItem.getReturnGoodsNumber() + afterSale.getNum());
                    break;
                }

                //判断当前售后的状态---已拒绝,买家取消售后,卖家终止售后
                case REFUSE:
                case BUYER_CANCEL:
                case SELLER_TERMINATION: {
                    orderItem.setReturnGoodsNumber(orderItem.getReturnGoodsNumber() - afterSale.getNum());
                    break;
                }
                default:
                    break;
            }
            //修改orderItem订单
            //订单状态不能为新订单,已失效订单或未申请订单才可以去修改订单信息
//            OrderItemAfterSaleStatusEnum afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.valueOf(orderItem.getAfterSaleStatus());
            OrderItemAfterSaleStatusEnum afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.EMPTY;
            if (orderItem.getAfterSaleStatus().equals(AfterSaleStatusEnum.NEW)) {
                // 如果是新建的订单
                afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.NEW;
            }
            if (orderItem.getAfterSaleStatus().equals(AfterSaleStatusEnum.PASS)) {
                // 如果已经通过了商家或者平台方审核
                afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.ALREADY_APPLIED;
            }
            if (orderItem.getAfterSaleStatus().equals(AfterSaleStatusEnum.APPLY)) {
                // 如果已经通过了商家或者平台方审核
                afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.ALREADY_APPLIED;
            }
            if (orderItem.getAfterSaleStatus().equals(OrderItemAfterSaleStatusEnum.NOT_APPLIED)) {
                // 如果是还未提交
                afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.NOT_APPLIED;
            }
            switch (afterSaleTypeEnum) {
                //售后状态为：未申请 部分售后 已申请
                case NOT_APPLIED:
                case PART_AFTER_SALE:
                case ALREADY_APPLIED: {
                    //通过正在售后商品总数修改订单售后状态
                    if (orderItem.getReturnGoodsNumber().equals(orderItem.getNum())) {
                        //修改订单的售后状态--已申请
                        orderItem.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.ALREADY_APPLIED.name());
                    } else if (orderItem.getReturnGoodsNumber().equals(0)) {
                        //修改订单的售后状态--未申请
                        orderItem.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.NOT_APPLIED.name());
                    } else {
                        //修改订单的售后状态--部分售后
                        orderItem.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.PART_AFTER_SALE.name());
                    }
                    break;
                }

                default:
                    break;
            }


            // 记录日志
            OrderLogEntity orderLog = new OrderLogEntity();
            orderLog.setOrderSn(orderItem.getOrderSn());
            orderLog.setCreateTime(new Date());
            orderLog.setOperatorType(dto.getOperatorType());
            orderLog.setOperatorId(dto.getOperatorId());
            orderLog.setOperatorName(dto.getOperatorName());
            orderLog.setMessage("订单[" + orderItem.getOrderSn() + "] " + UserEnums.valueOf(dto.getOperatorType()).getRole() + " 取消售后");

            AfterSaleLogEntity afterSaleLog = new AfterSaleLogEntity();
            afterSaleLog.setSn(dto.getAfterSaleSn());
            afterSaleLog.setCreateTime(new Date());
            afterSaleLog.setOperatorType(dto.getOperatorType());
            afterSaleLog.setOperatorId(dto.getOperatorId());
            afterSaleLog.setOperatorName(dto.getOperatorName());
            afterSaleLog.setMessage("售后-" + UserEnums.valueOf(dto.getOperatorType()).getRole() + "取消当前售后:单号:[" + dto.getAfterSaleSn() + "]");

            // 保存日志
            orderLogService.save(orderLog);
            afterSaleLogService.save(afterSaleLog);

            //根据售后编号修改售后单
            boolean updateAfterSale = this.updateById(afterSale);
            // 修改订单项
            boolean updateOrderItem = orderItemService.updateById(orderItem);

            if (updateAfterSale && updateOrderItem) {
                return RespBean.success("取消成功");
            } else {
                return RespBean.error("取消失败");
            }
        }

        return RespBean.error("当前售后单无法取消");
    }

    /**
     * 卖家确认收货
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean confirm(SellerAfterSaleConfirmDto dto) {
        AfterSaleEntity afterSale = getBySn(dto.getAfterSaleSn());

        //判断是否为已邮寄售后单
        if (!afterSale.getServiceStatus().equals(AfterSaleStatusEnum.BUYER_RETURN.name())) {
            return RespBean.error("售后状态错误，请刷新页面");
        }

        AfterSaleStatusEnum afterSaleStatusEnum;
        String pass = "PASS";
        //判断审核状态
        //在线支付 则直接进行退款
        if (pass.equals(dto.getServiceStatus()) &&
                afterSale.getRefundWay().equals(AfterSaleRefundWayEnum.ORIGINAL.name())) {
//            refundSupport.refund(afterSale); // 退款功能未开发
            afterSaleStatusEnum = AfterSaleStatusEnum.COMPLETE;
        } else if (pass.equals(dto.getServiceStatus())) {
            afterSaleStatusEnum = AfterSaleStatusEnum.WAIT_REFUND;
        } else {
            afterSaleStatusEnum = AfterSaleStatusEnum.SELLER_TERMINATION;
        }
        afterSale.setServiceStatus(afterSaleStatusEnum.name());
        afterSale.setAuditRemark(dto.getRemark());



        //根据售后状态。修改OrderItem订单中正在售后商品数量及状态
//        this.updateOrderItemAfterSaleStatus(afterSale);
        OrderItemEntity orderItem = orderItemService.getOne(new QueryWrapper<OrderItemEntity>()
                .eq("order_sn", afterSale.getOrderSn())
                .eq("sku_id", afterSale.getSkuId()));
        afterSaleStatusEnum = AfterSaleStatusEnum.valueOf(afterSale.getServiceStatus());
        switch (afterSaleStatusEnum) {
            //判断当前售后的状态---申请中
            case APPLY: {
                orderItem.setReturnGoodsNumber(orderItem.getReturnGoodsNumber() + afterSale.getNum());
                break;
            }

            //判断当前售后的状态---已拒绝,买家取消售后,卖家终止售后
            case REFUSE:
            case BUYER_CANCEL:
            case SELLER_TERMINATION: {
                orderItem.setReturnGoodsNumber(orderItem.getReturnGoodsNumber() - afterSale.getNum());
                break;
            }
            default:
                break;
        }
        orderItem.setAfterSaleStatus(AfterSaleStatusEnum.valueOf(dto.getServiceStatus()).name());
        //订单状态不能为新订单,已失效订单或未申请订单才可以去修改订单信息
        OrderItemAfterSaleStatusEnum afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.EMPTY;
        if (orderItem.getAfterSaleStatus().equals(AfterSaleStatusEnum.NEW)) {
            // 如果是新建的订单
            afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.NEW;
        }
        if (orderItem.getAfterSaleStatus().equals(AfterSaleStatusEnum.PASS)) {
            // 如果已经通过了商家或者平台方审核
            afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.ALREADY_APPLIED;
        }
        if (orderItem.getAfterSaleStatus().equals(AfterSaleStatusEnum.APPLY)) {
            // 如果已经通过了商家或者平台方审核
            afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.ALREADY_APPLIED;
        }
        if (orderItem.getAfterSaleStatus().equals(OrderItemAfterSaleStatusEnum.NOT_APPLIED)) {
            // 如果是还未提交
            afterSaleTypeEnum = OrderItemAfterSaleStatusEnum.NOT_APPLIED;
        }
        switch (afterSaleTypeEnum) {
            //售后状态为：未申请 部分售后 已申请
            case NOT_APPLIED:
            case PART_AFTER_SALE:
            case ALREADY_APPLIED: {
                //通过正在售后商品总数修改订单售后状态
                if (orderItem.getReturnGoodsNumber().equals(orderItem.getNum())) {
                    //修改订单的售后状态--已申请
                    orderItem.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.ALREADY_APPLIED.name());
                } else if (orderItem.getReturnGoodsNumber().equals(0)) {
                    //修改订单的售后状态--未申请
                    orderItem.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.NOT_APPLIED.name());
                } else {
                    //修改订单的售后状态--部分售后
                    orderItem.setAfterSaleStatus(OrderItemAfterSaleStatusEnum.PART_AFTER_SALE.name());
                }
                break;
            }

            default:
                break;
        }

        // 生成日志

        AfterSaleLogEntity afterSaleLog = new AfterSaleLogEntity();
        afterSaleLog.setSn(afterSale.getSn());
        afterSaleLog.setCreateTime(new Date());
        afterSaleLog.setOperatorType(dto.getOperatorType());
        afterSaleLog.setOperatorId(dto.getOperatorId());
        afterSaleLog.setOperatorName(dto.getOperatorName());
        if (dto.getServiceStatus().equals(AfterSaleStatusEnum.PASS)) {
            afterSaleLog.setMessage("售后-商家收货:单号["+dto.getAfterSaleSn()+ ",处理结果[商家收货]" );
        }
        if (dto.getServiceStatus().equals(AfterSaleStatusEnum.REFUSE)) {
            afterSaleLog.setMessage("售后-商家收货:单号["+dto.getAfterSaleSn()+ ",处理结果[商家拒收]" );
        }

        // 保存
        afterSaleLogService.save(afterSaleLog);
        //根据售后编号修改售后单
        boolean updateAfterSale = this.updateById(afterSale);
        boolean updateOrderItem = orderItemService.updateById(orderItem);
        if (updateAfterSale && updateOrderItem){
            return RespBean.success("收货成功");
        }else {
            return RespBean.error("收货失败");
        }
    }

    /**
     * 获取售后物流信息
     * @param sn
     * @return
     */
    @Override
    public RespBean getAfterSaleDeliveryTraces(String sn) {
        AfterSaleEntity afterSale = getBySn(sn);
        Map<String,Object> result = new HashMap<>();
        result.put("shipper",afterSale.getMLogisticsName()); // 物流公司
        result.put("logisticCode",afterSale.getMLogisticsNo()); // 快递单号
        List<Object> traces = new ArrayList<>(); // 物流信息 未实现
        result.put("traces",traces);

        return RespBean.success("获取成功",result);
    }

    // 根据商家id获取 商家售后收件地址
    private StoreAfterSaleAddressDTO getStoreAfterSaleAddressDTO(Long storeId) {
//        StoreAfterSaleAddressDTO storeAfterSaleAddressDTO = this.baseMapper.getStoreAfterSaleAddressDTO(storeId);
//        if (storeAfterSaleAddressDTO == null) {
//            storeAfterSaleAddressDTO = new StoreAfterSaleAddressDTO();
//        }
        RespBean storeAfterSaleAddressResp = storeFeignService.getStoreAfterSaleAddress(storeId);
        if (storeAfterSaleAddressResp.getObj() == null) {
            return null;
        }
        StoreAfterSaleAddressDTO storeAfterSaleAddressDTO =
                JSON.parseObject(JSON.toJSONString(storeAfterSaleAddressResp.getObj()), StoreAfterSaleAddressDTO.class);
        return storeAfterSaleAddressDTO;
    }

    /**
     * 根据sn后去售后信息
     *
     * @param sn
     * @return
     */
    private AfterSaleEntity getBySn(String sn) {
        QueryWrapper<AfterSaleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sn", sn);
        return this.getOne(queryWrapper);
    }

    private RespBean addAfterSale(AfterSaleDTO dto) {
        AfterSaleEntity afterSale = new AfterSaleEntity();
        BeanUtil.copyProperties(dto, afterSale);

        //写入会员信息
        afterSale.setMemberId(dto.getMemberId());
        afterSale.setMemberName(dto.getUsername());

        //写入商家信息
        OrderItemEntity orderItem = orderItemService.getById(dto.getOrderItemId());
        OrderEntity order = orderService.getOne(new QueryWrapper<OrderEntity>().eq("sn", orderItem.getOrderSn()));
        afterSale.setStoreId(order.getStoreId());
        afterSale.setStoreName(order.getStoreName());
        //写入订单商品信息
        afterSale.setGoodsImage(orderItem.getImage());
        afterSale.setGoodsName(orderItem.getGoodsName());
        afterSale.setSpecs(orderItem.getSpecs());
        afterSale.setFlowPrice(orderItem.getFlowPrice());
        //写入交易流水号
        afterSale.setTradeSn(order.getTradeSn());
        afterSale.setOrderSn(order.getSn());
        afterSale.setPayOrderNo(order.getPayOrderNo());
        afterSale.setOrderItemSn(orderItem.getSn());
        //写入状态
        afterSale.setServiceStatus(AfterSaleStatusEnum.APPLY.name());

        //创建售后单号
        String afterSaleSn = "A" + IdWorker.getTimeId();
        afterSale.setSn(afterSaleSn);
        afterSale.setCreateTime(new Date());
        afterSale.setReason(dto.getReason());
        //是否包含图片
        if (dto.getImages() != null) {
            afterSale.setAfterSaleImage(dto.getImages());
        }

        if (afterSale.getNum().equals(orderItem.getNum())) {
            //计算退回金额
            afterSale.setApplyRefundPrice(orderItem.getFlowPrice());
        } else {
            //单价计算
            BigDecimal utilPrice = orderItem.getFlowPrice();
            afterSale.setApplyRefundPrice(utilPrice);
        }

        //添加订单日志
        OrderLogEntity orderLog = new OrderLogEntity();
        orderLog.setOrderSn(order.getSn());
        orderLog.setMessage("订单[" + order.getSn() + "]申请售后,原因:" + dto.getReason() + "退款方式:" + AfterSaleTypeEnum.valueOf(dto.getServiceType()).description());
        orderLog.setOperatorId(dto.getMemberId());
        orderLog.setOperatorName(dto.getUsername());
        orderLog.setOperatorType(UserEnums.MEMBER.name());
        orderLogService.save(orderLog);

        // 修改订单和订单项
        orderItem.setAfterSaleStatus(AfterSaleStatusEnum.APPLY.name());
        orderItemService.updateById(orderItem);

        //添加售后
        this.save(afterSale);
        // 添加售后日志
        AfterSaleLogEntity afterSaleLog = new AfterSaleLogEntity();
        afterSaleLog.setCreateTime(new Date());
        afterSaleLog.setSn(afterSaleSn);
        afterSaleLog.setMessage("订单[" + order.getSn() + "] " + "用户申请:" + AfterSaleTypeEnum.valueOf(dto.getServiceType()).description() + " 单号:[" + afterSaleSn + "]");
        afterSaleLog.setOperatorType(UserEnums.MEMBER.name());
        afterSaleLog.setOperatorId(dto.getMemberId());
        afterSaleLog.setOperatorName(dto.getUsername());
        afterSaleLogService.save(afterSaleLog);

        return RespBean.success("保存成功");

    }

    private boolean checkAfterSaleType(AfterSaleDTO dto) {
        //判断数据是否为空
        if (null == dto || CharSequenceUtil.isEmpty(String.valueOf(dto.getOrderItemId()))) {
            log.info("订单项不可售后，原因:订单不存在，订单项ID:{}", dto.getOrderItemId());
            return false;
        }
        //获取订单货物判断是否可申请售后
        OrderItemEntity orderItem = orderItemService.getById(dto.getOrderItemId());
        //未申请售后或部分售后订单货物才能进行申请
        if (!orderItem.getAfterSaleStatus().equals(OrderItemAfterSaleStatusEnum.NOT_APPLIED.name()) && !orderItem.getAfterSaleStatus().equals(OrderItemAfterSaleStatusEnum.PART_AFTER_SALE.name())) {
            log.info("订单项不可售后，原因:订单状态不允许申请售后，请联系平台或商家，订单项ID:{}", dto.getOrderItemId());
            return false;
        }

        //申请商品数量不能超过商品总数量-售后商品数量
        if (dto.getNum() > (orderItem.getNum() - orderItem.getReturnGoodsNumber())) {
            log.info("订单项不可售后，原因:申请售后商品数量错误，订单项ID:{}", dto.getOrderItemId());
            return false;
        }
        //获取售后类型
        OrderEntity order = orderService.getOne(new QueryWrapper<OrderEntity>().eq("sn", orderItem.getOrderSn()));
        AfterSaleTypeEnum afterSaleTypeEnum = AfterSaleTypeEnum.valueOf(dto.getServiceType());
        switch (afterSaleTypeEnum) {
            case RETURN_MONEY:
                //只处理已付款的售后
                if (!PayStatusEnum.PAID.description().equals(order.getPayStatus())) {
                    log.info("订单项不可售后，原因:订单状态不允许申请售后，请联系平台或商家，订单项ID:{}", dto.getOrderItemId());
                    return false;
                }
//                this.checkAfterSaleReturnMoneyParam(afterSaleDTO);
                break;
            case RETURN_GOODS:
                //是否为有效状态
                boolean availableStatus = CharSequenceUtil.equalsAny(order.getOrderStatus(), OrderStatusEnum.DELIVERED.name(), OrderStatusEnum.COMPLETED.name());
                if (!PayStatusEnum.PAID.description().equals(order.getPayStatus()) && availableStatus) {
                    log.info("订单项不可售后，原因:订单状态不允许申请售后，请联系平台或商家，订单项ID:{}", dto.getOrderItemId());
                    return false;
                }
                break;
            default:
                break;
        }
        return true;
    }
}